<?php
/* 
 * Copyright (c) 2018-2021   All rights reserved.
 *
 * 创建时间：2021-10-11 11:55:30
 *
 * 项目：/levmodules  -  $  - Form_lev_modules.php
 *
 * 作者：{{AUTO GENERATE}}
 */

//此文件使用程序自动生成，下次生成时【不会】覆盖。
//在这里可以补充、完善你的程序逻辑

namespace modules\levmodules\table\form\Form_lev_modules;

use Lev;
use lev\base\Modelv;
use lev\base\Viewv;
use lev\helpers\cacheFileHelpers;
use lev\helpers\ModulesHelper;
use modules\levmodules\controllers\AdminModulesController;
use modules\levmodules\helpers\generateControllerHelper;
use modules\levmodules\helpers\generateFormHelper;
use modules\levmodules\helpers\generateHelper;
use modules\levmodules\helpers\generatePagesHelper;
use modules\levmodules\helpers\zipHelper;
use modules\levmodules\table\form\Form_lev_modules\_gen\BaseForm_lev_modules;

!defined('INLEV') && exit('Access Denied LEV');

class BaseForm_lev_modulesMiddle extends BaseForm_lev_modules
{
    public static $formPrexx = '';

    public static function setFormSettings($settings, $result = [])
    {
        empty($result['identifier']) ||
        Lev::$app['inputOptionInit']['#iden'] = $result['identifier'];//传递给字段设置项 levmodulesSetHelper::settableName()
        return parent::setFormSettings($settings, $result); // TODO: Change the autogenerated stub
    }

    public static function saveForm($formPre = 'datax', $route = '', $form = null, $upData = null, $upDataForce = null, $opInfo = null)
    {
        static::$formPrexx = $formPre;

        $opid   = intval(Lev::GPv('opid'));
        $opInfo = $opid >0 ? static::findOne(['id'=>$opid]) : [];

        $postData = Lev::stripTags(Lev::POSTv($formPre)) ?: [];
        $upData   = $postData + $opInfo;

        if (empty($upData['name'])) {
            return Modelv::errorMsg($formPre.'[name]', '模块名称不能为空', -2100);
        }
        if ($errMsg = static::isErrorVersion($upData['version'])) {
            return $errMsg;
        }

        $idenDir = $upData['classdir'] ? ModulesHelper::getIdenDir($upData['identifier'], $upData['classdir']) : $upData['identifier'];
        if ($errMsg = static::checkErrorIden($idenDir)) {
            return $errMsg;
        }
        if (ModulesHelper::findOne("identifier='".$upData['identifier']."' AND id<>$opid")) {
            return Modelv::errorMsg($formPre.'[identifier]', '模块标识已存在', -2203);
        }

        empty($upData['version'])   && $upData['version']   = date('Ymd', Lev::$app['timestamp']).'.01';
        empty($upData['copyright']) && $upData['copyright'] = 'Lev';

        $upDataForce['versiontime'] = Lev::$app['timestamp'];//print_r($upData);exit;

        $rs = parent::saveForm($formPre, $route, $form, $upData, $upDataForce, $opInfo); // TODO: Change the autogenerated stub
        if (isset($rs['succeed']) && $rs['status'] >0) {
            $opid = $rs['opid'];
            $opInfo = static::findOne(['id'=>$opid]);
            $settings = Lev::getSettings($opInfo['settings']);

            if (static::checkGenerateAdminFiles()) {
                generateControllerHelper::createAdminController($upData['identifier'], Lev::getSettings($settings['_adminNavs']));
            }
            if (static::checkGenerateAdminFormFiles()) {
                generateFormHelper::createAdminForm($upData['identifier'], Lev::getSettings($settings['_forms']));
            }

            if (static::checkGeneratePagesFiles()) {
                generatePagesHelper::createPagesController($upData['identifier'], Lev::getSettings($settings['_pageNavs']));
            }

            $upData['navTitle'] = $upData['settings___navTitle'];

            static::checkGenerateFiles() &&
            $rs['##createModule'] = generateHelper::createModule($upData['identifier'], $upData);

            isset($postData['settings___dzinstall']) && empty($upData['settings___dzinstall']) &&
            $rs['##createDzplugin'] = generateHelper::createDzplugin($upData['identifier'], $upData);

            generateHelper::isExistIden($idenDir) && static::doExport($opid);
            ModulesHelper::setCaches();
        }
        return $rs;
    }

    public static function checkGeneratePagesFiles() {
        return ($gm = Lev::GPv('generatePagesFiles')) !== null && !$gm;
    }

    public static function checkGenerateFiles() {
        return ($gm = Lev::GPv('generateFiles')) !== null && !$gm;
    }

    public static function checkGenerateAdminFiles() {
        return ($gm = Lev::GPv('generateAdminFiles')) !== null && !$gm;
    }

    public static function checkGenerateAdminFormFiles() {
        return ($gm = Lev::GPv('generateAdminFormFiles')) !== null && !$gm;
    }

    /**
     * @return string|array
     */
    public static function doExport($opid = 0, $preview = false, $mudInfo = null) {
        !$opid && $opid = intval(Lev::GPv('opid'));
        $inLev = zipHelper::getCheckINLEVphpcode();
        $settings = $mudInfo ?: ModulesHelper::findOne(['id'=>$opid]);
        //$settings['versiontime'] = Lev::$app['timestamp'];
        //ModulesHelper::update(['versiontime'=>Lev::$app['timestamp']], ['id'=>$mudInfo['id']]);

        unset($settings['status']);
        $settings = static::getExportData($settings);

//        $sets = Lev::getSettings($settings['settings']);
//        $sets['columns'] = static::getModuleTableColumnsComment($sets['dropTables']);
//        $settings['settings'] = Lev::setSettings($sets);

        $data = '<?php '.$inLev.' return ' . cacheFileHelpers::varExportSerialize($settings) . ';';
        if ($preview) {//预览
            return $data;
        }

        //$settings['classdir'] && $settings['status'] = 1;
        $file = Lev::getAlias('@modules/'.ModulesHelper::getIdenDir($settings['identifier'], $settings['classdir']).'/migrations/data/');
        cacheFileHelpers::mkdirv($file);
        file_put_contents($file . 'moduleinfo.php', $data);
        return (Lev::responseMsg());
    }
    public static function getExportData($data) {
        unset($data['id'], $data['typeid']);
        return $data;
    }

    public static function banIdens($iden) {
        if ($iden === 'levmodules') {
            return false;
        }
        $banIdens = ['module'];
        foreach ($banIdens as $v) {
            if (stripos($iden, $v) !== false) {
                $tip = '模块标识关键字【'.str_ireplace($v, '<b class="red">'.$v.'</b>', $iden).'】被占用';
                return Modelv::errorMsg(static::$formPrexx.'[identifier]', $tip, -22022);
            }
        }
        return false;
    }
    public static function checkErrorIden($idenDir) {
        $iden = basename($idenDir);
        if ($msg = static::banIdens($iden)) {
            return $msg;
        }
        if (strpos($iden, 'tab__') === 0 || strpos($idenDir, '/tab__') !== false) {
            return Modelv::errorMsg(static::$formPrexx.'[identifier]', '模块标识禁止用占位符"tab__"开头', -2200);
        }
        if ($msg = self::isErrorIden($iden, static::$formPrexx.'[identifier]')) {
            return $msg;
        }
        if (static::checkGenerateFiles() && generateHelper::isExistIden($idenDir)) {
            return Modelv::errorMsg(static::$formPrexx.'[identifier]', '模块标识目录已存在，不支持重复生成模块目录', -2202);
        }
        return false;
    }
    public static function isErrorIden($iden, $inputname = 'identifier') {
//        if (!preg_match('/^[a-zA-Z][a-zA-Z0-9_]+$/', $iden)) {
//            return Modelv::errorMsg($inputname, '只允许a-z、0-9和下划线必须以字母开头', -2201);
//        }
//        return false;
        return ModulesHelper::isErrorIden($iden, $inputname);
    }
    public static function isErrorVersion($string, $inputname = '', $tipname = '版本号') {
        return $string ? ModulesHelper::isErrorVersion($string, $inputname ?: static::$formPrexx.'[version]', $tipname) : false;
    }
}


class Form_lev_modules extends BaseForm_lev_modulesMiddle {

    public static function setupDesc()
    {
        $arr = parent::setupDesc(); // TODO: Change the autogenerated stub
        return array(
                '1'  => '模块基本信息',

                '3'  => '商城售卖价格(元)',

                '4'  => '管理导航(控制器生成)',
                '6'  => '前台页面(控制器生成)',

                '7'  => '模块表单(表单生成)',

                '11' => 'DZ安装文件生成',

            );// + $arr;
    }

    public static function extInputs()
    {
        //return parent::extInputs(); // TODO: Change the autogenerated stub
        $setup = Lev::GPv('setup') ?: 1;
        $arr = [];

        $setup == 1 &&
        $arr['generateFiles'] = array(
                'moduleidentifier' => 'levmodules',
                'classify'         => 'lev_modules',
                'title'            => '模块文件生成开关',
                'placeholder'      => '<tips>创建模块文件到目录:'.Lev::$aliases['@modules'].'/唯一标识</tips>',
                'inputname'        => 'generateFiles',
                'inputtype'        => 'radio',
                'inputvalue'       => 1,
                'settings'         => '',
                'displayorder'     => '6',
                'status'           => '1',
        );

        $setup == 4 &&
        $arr['generateAdminFiles'] =  array(
                'moduleidentifier' => 'levmodules',
                'classify'         => 'lev_modules',
                'title'            => '控制器文件生成开关',
                'placeholder'      => ' 开启后，为【数据表】创建控制器文件（自动生成）以及表单文件，强制生成也需要开启 ',
                'inputname'        => 'generateAdminFiles',
                'inputtype'        => 'radio',
                'inputvalue'       => 1,
                'settings'         => '',
                'displayorder'     => '6',
                'status'           => '1',
        );

        $setup == 6 &&
        $arr['generatePagesFiles'] =  array(
            'moduleidentifier' => 'levmodules',
            'classify'         => 'lev_modules',
            'title'            => '前台页面生成开关',
            'placeholder'      => ' 开启后，才可以生成文件，强制生成也需要开启<br><tips>【重要】它将覆盖原有生成文件，需开启自动生成</tips>
 <br><tips>已生成的控制器在不知情的情况下不要强制生成，它将覆盖原有文件而发生改变</tips>',
            'inputname'        => 'generatePagesFiles',
            'inputtype'        => 'radio',
            'inputvalue'       => 1,
            'settings'         => '',
            'displayorder'     => '6',
            'status'           => '1',
        );
        $setup == 7 &&
        $arr['generateAdminFormFiles'] =  array(
            'moduleidentifier' => 'levmodules',
            'classify'         => 'lev_modules',
            'title'            => '表单文件生成开关',
            'placeholder'      => ' 开启后，才可以生成文件，强制生成也需要开启 ',
            'inputname'        => 'generateAdminFormFiles',
            'inputtype'        => 'radio',
            'inputvalue'       => 1,
            'settings'         => '',
            'displayorder'     => '6',
            'status'           => '1',
        );
        return $arr;
    }

    public static function headerHtm()
    {
        //return parent::headerHtm(); // TODO: Change the autogenerated stub
        return Viewv::renderPartial(AdminModulesController::$tmpPath . '/myself/form_header_htm', [
        ]);
    }

    public static function footerHtm()
    {
        //return parent::footerHtm(); // TODO: Change the autogenerated stub
        return '<tips class="gray inblk scale8">自定义footerHtm</tips>';
    }

    public static function footerFormInnerHtm()
    {
        //return parent::footerFormInnerHtm(); // TODO: Change the autogenerated stub
        return '<tips class="gray inblk scale8">自定义footerFormInnerHtm</tips>';
    }

    public static function allColumns()
    {
        return parent::allColumns(); // TODO: Change the autogenerated stub
    }

    public static function safeColumnsInpus($columns)
    {
        return parent::safeColumnsInpus($columns); // TODO: Change the autogenerated stub
    }

    public static function setFormSettings($settings, $result = [])
    {
        return parent::setFormSettings($settings, $result); // TODO: Change the autogenerated stub
    }

    public static function saveInputs($datas, $where = [], $inId = false, $tables = [], $inputs = [], $formSet = true, $tablesFormData = [])
    {
        return parent::saveInputs($datas, $where, $inId, $tables, $inputs, $formSet, $tablesFormData); // TODO: Change the autogenerated stub
    }

    public static function getNextSetup()
    {
        return parent::getNextSetup(); // TODO: Change the autogenerated stub
    }

    public static function inputsSetup()
    {
        return parent::inputsSetup(); // TODO: Change the autogenerated stub
    }

}